<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { getUserAddress } from '@/apis/address';
import { ElMessage } from 'element-plus';

// 获取用户地址列表
const tableData = ref([]);

onMounted(async () => {
  const res = await getUserAddress();
  console.log(res);
  if (res.data && Array.isArray(res.data)) {
    tableData.value = res.data.map(item => ({
      address: item.address,
      contact: item.contact,
      receiver: item.receiver,
      fullLocation: item.fullLocation
    }));
  }
});

// 新地址信息或编辑时的当前地址信息
const newAddress = reactive({
  id: null, // 如果有唯一标识符，可以使用它来追踪编辑的条目
  receiver: '',
  contact: '',
  address: '',
  fullLocation: ''
});

// 控制弹窗显示/隐藏
const dialogVisible = ref(false);

// 当前编辑的索引（如果是在编辑模式下）
let currentIndex = -1;

// 打开添加地址弹窗
const handleAddAddress = () => {
  Object.assign(newAddress, { id: null, receiver: '', contact: '', address: '', fullLocation: '' });
  currentIndex = -1;
  dialogVisible.value = true;
};

// 编辑现有地址
const handleEdit = (index: number, row: any) => {
  Object.assign(newAddress, { ...row, id: index }); // 使用索引作为临时ID
  currentIndex = index;
  dialogVisible.value = true;
};

// 提交新地址或编辑后的地址
const submitNewAddress = () => {
  if (newAddress.receiver && newAddress.contact && newAddress.address && newAddress.fullLocation) {
    if (currentIndex >= 0) {
      // 编辑模式：更新现有地址
      tableData.value[currentIndex] = { ...newAddress };
      ElMessage({
        message: '地址更新成功',
        type: 'success'
      });
    } else {
      // 添加模式：添加新地址
      tableData.value.push({ ...newAddress });
      ElMessage({
        message: '地址添加成功',
        type: 'success'
      });
    }
    // 清空表单
    Object.assign(newAddress, { id: null, receiver: '', contact: '', address: '', fullLocation: '' });
    dialogVisible.value = false;
  } else {
    ElMessage.error('请填写所有必填字段');
  }
};

// 删除地址
const handleDelete = (index: number) => {
  tableData.value.splice(index, 1);
  ElMessage({
    message: '地址删除成功',
    type: 'success'
  });
};
</script>

<template>
  <div class="box">
    <el-button type="primary" style="margin-left: 85%;" @click="handleAddAddress">添加地址</el-button>
    <el-table :data="tableData" style="width: 95%; margin-left: 20px; margin-top: 20px; border: 1px solid gainsboro;">
      <el-table-column prop="receiver" label="收货人姓名" width="120" />
      <el-table-column prop="contact" label="联系方式" width="120" />
      <el-table-column prop="address" label="收货地址" width="120" />
      <el-table-column prop="fullLocation" label="详细地址" width="300" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button link type="primary" size="small" @click="handleDelete(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑地址弹窗 -->
    <el-dialog v-model="dialogVisible" :title="currentIndex >= 0 ? '编辑地址' : '添加新地址'" width="30%">
      <el-form :model="newAddress">
        <el-form-item label="收货人姓名">
          <el-input v-model="newAddress.receiver"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="newAddress.contact"></el-input>
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="newAddress.address"></el-input>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="newAddress.fullLocation"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.box {
  margin: 20px 0;
}
</style>